package org.farm2.luser.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.farm2.auth.face.FarmParameter;
import org.farm2.auth.service.PostServiceInter;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.base.domain.FarmUserContextLoader;
import org.farm2.base.password.FarmPasswordEncoder;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.files.utils.FileDownloadUtils;
import org.farm2.luser.domain.LocalOrg;
import org.farm2.luser.domain.LocalUser;
import org.farm2.luser.dto.LocalUserDto;
import org.farm2.luser.dto.ResetPasswordDto;
import org.farm2.luser.service.LocalOrgServiceInter;
import org.farm2.luser.service.LocalUserServiceInter;
import org.farm2.report.FarmReport;
import org.farm2.tools.bean.FarmBeanUtils;
import org.farm2.tools.db.DataQuery;
import org.farm2.tools.db.DataQueryDto;
import org.farm2.tools.db.DataResult;
import org.farm2.tools.db.commons.DBSort;
import org.farm2.tools.db.commons.SqlRule;
import org.farm2.tools.web.FarmResponseCode;
import org.farm2.tools.web.FarmResponseResult;
import org.farm2.tools.web.dto.IdDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/localuser")
public class LocalUserController {
    @Autowired
    private LocalUserServiceInter localUserServiceImpl;
    @Autowired
    private LocalOrgServiceInter localOrgServiceImpl;
    @Autowired
    private PostServiceInter postServiceImpl;
    @Autowired
    private FarmParameter farmParameter;
    @Autowired
    private FileDownloadUtils fileDownloadUtils;
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private FarmReport farmReport;


    @PreAuthorize("@farmAction.has('localUser.report')")
    @PostMapping("/report")
    public void downloadFile(@RequestBody DataQueryDto query, HttpServletRequest request, HttpServletResponse response) throws Exception {
        query.setPageSize(1000);
        DataResult result = (DataResult) queryAll(query).getData();
        result.runFormatTime("LOGINTIME");
        result.runDictionary("1:系统用户,3:管理员", "TYPE");
        result.runDictionary("1:可用,0:禁用", "STATE");
        File reportFile = farmReport.addParas("result", result.getData()).generateFile("userList.xls");
        fileDownloadUtils.downloadFile(request, response, reportFile, reportFile.length(), reportFile.getName(), "application/octet-stream");
    }


    @PreAuthorize("@farmAction.has('localUser.down.tempate')")
    @PostMapping("/downtemplate")
    public void downloadTemplate(@RequestBody DataQueryDto query, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File templateFile = farmParameter.getClassPathFile(Paths.get("report", "userImpTemplet.xls"));
        fileDownloadUtils.downloadFile(request, response, templateFile, templateFile.length(), templateFile.getName(), "application/octet-stream");
    }


    /**
     * 导入报表
     *
     * @param fileid
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.import')")
    @PostMapping("/import")
    public FarmResponseResult importData(@RequestBody IdDto fileid) throws InterruptedException {
        localUserServiceImpl.importUser(fileid.getId());
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
    }



    /**
     * 条件查询
     *
     * @param query
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.query')")
    @PostMapping("/query")
    public FarmResponseResult queryAll(@RequestBody DataQueryDto query) {
        DataQuery dataQuery = DataQuery.getInstance(query);
        if ("NONE".equals(dataQuery.getRuleValue("ORGID")) || dataQuery.getRuleValue("ORGID") == null) {
            dataQuery.removeRule("ORGID");
        } else {
            LocalOrg org = localOrgServiceImpl.getLocalOrgById((String) dataQuery.getRuleValue("ORGID"));
            dataQuery.removeRule("ORGID");
            dataQuery.addRule(new SqlRule(" and (TREECODE like '?%')", org.getTreecode()));
        }
        dataQuery.addDefaultSort(new DBSort("ETIME", DBSort.SORT_TYPE.DESC));
        dataQuery.setRuleAsSql("default", " and (A.NAME like '%?%'  or LOGINNAME like '%?%')");
        DataResult result = localUserServiceImpl.searchLocalUser(dataQuery);

        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, result);
    }

    /**
     * 添加数据
     *
     * @param localUserDto
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.add')")
    @PostMapping
    public FarmResponseResult addSubmit(@Valid @RequestBody LocalUserDto localUserDto) {
        LocalUser user = localUserServiceImpl.insertLocalUserEntity(FarmBeanUtils.copyProperties(localUserDto, new LocalUser()));
        postServiceImpl.savePostUser(user.getLoginname(), localUserDto.getPost());
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, user.getId());
    }

    /**修改数据
     * @param id
     * @param localUserDto
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.edit')")
    @PutMapping("/{id}")
    public FarmResponseResult editSubmit(@PathVariable String id, @Valid @RequestBody LocalUserDto localUserDto) {
        localUserDto.setId(id);
        localUserServiceImpl.editLocalUserEntity(FarmBeanUtils.copyProperties(localUserDto, new LocalUser()));
        LocalUser user = localUserServiceImpl.getLocalUserById(id);
        postServiceImpl.savePostUser(user.getLoginname(), localUserDto.getPost());
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
    }

    /**删除数据
     * @param id
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.del')")
    @DeleteMapping("/{id}")
    public FarmResponseResult delSubmit(@PathVariable String id) {
        localUserServiceImpl.delLocalUser(id);
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, id);
    }


    /**
     * 重置用户密码（默认密码）
     *
     * @param ids
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.resetpassword')")
    @PostMapping("/defaultpassword")
    public FarmResponseResult defaultpassword(@RequestBody List<String> ids) {
        for (String id : ids) {
            localUserServiceImpl.reSetPassword(id, farmParameter.getStringParameter("farm2.config.password.default"));
        }
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
    }


    /**
     * 重置用户密码（指定密码）
     *
     * @param data
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.resetpassword')")
    @PostMapping("/resetpassword")
    public FarmResponseResult resetPassword(@RequestBody ResetPasswordDto data) {
        FarmPasswordEncoder passwordEncoder = new FarmPasswordEncoder();
        LocalUser localUser = localUserServiceImpl.getLocalUserByLoginName(data.getLoginname());
        if (passwordEncoder.matches(data.getWebPassword(), passwordEncoder.getSaltByCode(data.getCode()), localUser.getPassword())) {
            for (String loginname : data.getUserkeys()) {
                localUserServiceImpl.resetPasswordByDbPassword(loginname, data.getNewSysPassword());
            }
            return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
        } else {
            return FarmResponseResult.getInstance(FarmResponseCode.ERROR, FarmPasswordEncoder.MATCHES_FALSEMSG, null);
        }
    }



    /**
     * 批量删除数据
     *
     * @param ids 要删除的记录ID列表
     * @return 操作结果
     */
    @PreAuthorize("@farmAction.has('localUser.del')")
    @DeleteMapping("/batch")
    public FarmResponseResult batchDelSubmit(@RequestBody List<String> ids) {
        for (String id : ids) {
            localUserServiceImpl.delLocalUser(id);
        }
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
    }

    /**数据浏览
     * @param id
     * @return
     */
    @PreAuthorize("@farmAction.has('localUser.info')")
    @GetMapping("/{id}")
    public FarmResponseResult info(@PathVariable String id) {
        LocalUser localUser = localUserServiceImpl.getLocalUserById(id);
        LocalUserDto user = FarmBeanUtils.copyProperties(localUser, new LocalUserDto());
        List<String> posts = postServiceImpl.getUserPost(user.getLoginname());
        user.setPost(posts);
        return new FarmResponseResult(FarmResponseCode.SUCESS, user);
    }
}
